package Game;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class Cannon {
    //属性
    int x,y;
    int fire;
    int score;
    Image img;
    Image[] imgs = new Image[5];
    int currentImgIndex = 0;
    double rotationAngleCannon;
    //构造
    public Cannon(){
        x=550;
        y=700;
        fire = 1;
        score = 0;
        img = new ImageIcon("img/1.png").getImage();
        for(int i=0;i<imgs.length;i++){
            imgs[i] = new ImageIcon("img/"+(i+1)+".png").getImage();
        }
        // 默认炮口朝上（角度为-90度，因为Java坐标系中Y轴向下）
        rotationAngleCannon = 0;
    }
    //切换到下一张图片
    public void nextImage() {
        currentImgIndex = (currentImgIndex + 1) % imgs.length;
        img = imgs[currentImgIndex];
    }


    // 根据鼠标位置计算旋转角度（修改参数为鼠标坐标）
    public void calculateRotation(int mouseX, int mouseY) {
        double dx = mouseX - x;
        double dy = mouseY - y;

        // 计算角度（atan2返回的角度范围是[-π, π]，转换为度）
        rotationAngleCannon = Math.toDegrees(Math.atan2(dy, dx)) + 90;
    }

    // 获取旋转后的图片
    public Image getRotatedImage() {
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        BufferedImage rotated = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 以图片中心为原点旋转
        g2d.rotate(Math.toRadians(rotationAngleCannon), width / 2, height / 2);
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();
        return rotated;
    }
}
